package inetAddressDemo;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
/**
 * 
 * InetAddress只要ip地址相等这2个对象就相等
 *	
 * NetworkInterface表示物理地址和虚拟地址
 */
public class InetAddressDemo {

	public static void main(String[] args) throws IOException {
		InetAddress inetAddress=InetAddress.getByName("127.0.0.1");
		NetworkInterface nwInterface=NetworkInterface.getByName("lo");
		
		
		System.out.println(NetworkInterface.getByInetAddress(inetAddress));
		System.out.println(nwInterface);
		
		Enumeration<NetworkInterface> inets=NetworkInterface.getNetworkInterfaces();
		while(inets.hasMoreElements()){
			NetworkInterface net=inets.nextElement();
			Enumeration<InetAddress> adds=net.getInetAddresses();
			while(adds.hasMoreElements()){
				System.out.println(adds.nextElement().getHostAddress());
			}
			System.out.println();
		}
		/*InetAddress inetAddress=InetAddress.getByName("www.baidu.com");
		System.out.println(inetAddress.isReachable(1000));
		System.out.println("ip:"+inetAddress.getHostAddress());
		System.out.println("hostName:如果不知道主机名就会返回ip地址:"+inetAddress.getHostName());
		System.out.println("hostName:不论知不知道主机名都会联系DNS服务器:"+inetAddress.getCanonicalHostName());
		
		InetAddress inetAddressLocal=InetAddress.getLocalHost();
		System.out.println(inetAddressLocal.getHostAddress());
		System.out.println(inetAddressLocal.getHostName());*/
	}
	 
	/**
	 * 检查ip地址的版本
	 * @param inetAddress
	 * @return
	 */
	public static Integer getVersion(InetAddress inetAddress){
		byte[] address=inetAddress.getAddress();
		if(address.length==4){
			return 4;
		}else if(address.length==6){
			return 6;
		}else{
			return -1;
		}
	}

}
